/**
 * Copyright (c) 2024 Hunan OpenValley Digital Industry Development Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include "GPUImageHueFilter.h"

const std::string GPUImageHueFilter::HUE_FRAGMENT_SHADER = R"(
    #extension GL_OES_EGL_image_external : require
    precision highp float;
    varying highp vec2 textureCoordinate;
    
    uniform samplerExternalOES inputImageTexture;
    uniform mediump float hueAdjust;
    const highp vec4 kRGBToYPrime = vec4 (0.299, 0.587, 0.114, 0.0);
    const highp vec4 kRGBToI = vec4 (0.595716, -0.274453, -0.321263, 0.0);
    const highp vec4 kRGBToQ = vec4 (0.211456, -0.522591, 0.31135, 0.0);
    
    const highp vec4 kYIQToR = vec4 (1.0, 0.9563, 0.6210, 0.0);
    const highp vec4 kYIQToG = vec4 (1.0, -0.2721, -0.6474, 0.0);
    const highp vec4 kYIQToB = vec4 (1.0, -1.1070, 1.7046, 0.0);
    
    void main ()
    {
        // Sample the input pixel
        highp vec4 color = texture2D(inputImageTexture, textureCoordinate);
        
        // Convert to YIQ
        highp float YPrime = dot (color, kRGBToYPrime);
        highp float I = dot (color, kRGBToI);
        highp float Q = dot (color, kRGBToQ);
        
        // Calculate the hue and chroma
        highp float hue = atan (Q, I);
        highp float chroma = sqrt (I * I + Q * Q);
        
        // Make the user's adjustments
        hue += (-hueAdjust); //why negative rotation?
        
        // Convert back to YIQ
        Q = chroma * sin (hue);
        I = chroma * cos (hue);
        
        // Convert back to RGB
        highp vec4 yIQ = vec4 (YPrime, I, Q, 0.0);
        color.r = dot (yIQ, kYIQToR);
        color.g = dot (yIQ, kYIQToG);
        color.b = dot (yIQ, kYIQToB);
        
        // Save the result
        gl_FragColor = color;
    }
)";

GPUImageHueFilter::GPUImageHueFilter() : hue(90.0f) {}

GPUImageHueFilter::GPUImageHueFilter(const float hueValue)
    : GPUImageFilter(NO_FILTER_VERTEX_SHADER, HUE_FRAGMENT_SHADER)
{
    hue = hueValue;
}

void GPUImageHueFilter::onInit()
{
    GPUImageFilter::onInit();
    hueLocation = glGetUniformLocation(getProgram(), "hueAdjust");
}

void GPUImageHueFilter::onInitialized()
{
    GPUImageFilter::onInitialized();
    setHue(hue);
}

void GPUImageHueFilter::setHue(const float hueValue)
{
    hue = hueValue;
    float hueAdjust = static_cast<float>(this->hue) * (M_PI / 180.0f);
    setFloat(hueLocation, hueAdjust);
}